package com.ccx.ocr;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.ExifInterface;
import android.content.res.AssetManager;
import android.media.FaceDetector;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.text.method.ScrollingMovementMethod;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONException;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MyOcr extends CordovaPlugin {
    private static final String TAG = com.ccx.ocr.MyOcr.class.getSimpleName();

    protected Predictor predictor = new Predictor();

    @Override
    protected void pluginInitialize() {
        super.pluginInitialize();

        boolean res = onLoadModel();
        Log.i(TAG, "load model: " + res);

        Log.d(TAG, "plugin initialized.");
    }

    @Override
    public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {
        Log.d(TAG, String.format("%s is called. Callback ID: %s.", action, callbackContext.getCallbackId()));

        if (action.equals("ocr")) {
            return ocr(args, callbackContext);
        }

        return false;
    }

    public boolean onLoadModel() {
        if (predictor.isLoaded()) {
            predictor.releaseModel();
        }
        return predictor.init(cordova.getContext(), "models/ch_PP-OCRv2", "labels/ppocr_keys_v1.txt", 0, 4,
                "LITE_POWER_HIGH",
                960, 0.1f);  // 960
    }

    private boolean ocr(CordovaArgs args, final CallbackContext callbackContext) {
        cordova.getThreadPool().execute(() -> {
            try {
                String imgBase64 = args.getString(0);
                imgBase64 = imgBase64.substring(imgBase64.indexOf(",") + 1);
                byte[] imgByte = Base64.decode(imgBase64, Base64.DEFAULT);
                Bitmap img = BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
                predictor.setInputImage(img);
                boolean res = predictor.runModel(1, 1, 1);
                if(res){
                    String outText = predictor.getOutputText();
                    String outImg = predictor.getOutputImgBase64();
                    callbackContext.success(outText + "&&##&&" + outImg);
                } else {
                    callbackContext.error("failed!");
                }
            } catch (Exception e) {
                callbackContext.error(e.getMessage());
            }
        });
        return true;
    }

}
